<template>
    <div class="container f">
        <!-- 设备面板 -->
        <div class="device-panel">
            <div class="title">装置</div>
            <div class="list">
                <div class="name">
                    <span>————</span>
                    <span class="n"> 设备 </span>
                    <span>————</span>
                </div>
                <div class="box f fpj">
                    <template v-for="item in devices" :key="item.id">
                        <div class="item f fac fpc"
                            v-if="item.type == 'device'" 
                            @mousedown="startDrag($event, item)" 
                            :style="{'background': `URL('${item.imageUrl}') center no-repeat`, 'backgroundSize': 'contain'}"
                            >
                        </div>
                    </template>
                </div>
                <div class="name">
                    <span>————</span>
                    <span class="n"> 线段 </span>
                    <span>————</span>
                </div>
                <div class="box f fpj">
                    <template v-for="item in devices" :key="item.id">
                        <!-- 实线 -->
                        <div v-if="item.type == 'line' && item.device == 'line-solid'" @mousedown="startDrag($event, item)"  class="line"></div>
                        <!-- 虚线 -->
                        <div v-if="item.type == 'line' && item.device == 'line-dashed'" @mousedown="startDrag($event, item)"  class="dashed line"></div>
                        <!-- 圆弧 -->
                        <div v-if="item.type == 'line' && item.device == 'line-arc'" @mousedown="startDrag($event, item)"  class="arc-line"><div class="arc"></div></div>
                        <!-- 带箭头 -->
                        <div v-if="item.type == 'line' && item.device == 'line-arrow'" @mousedown="startDrag($event, item)"  class="arrow line"></div>
                    </template>
                </div>
                <div class="name">
                    <span>————</span>
                    <span class="n"> 文字 </span>
                    <span>————</span>
                </div>
                <div class="box f fpj">
                    <template v-for="item in devices" :key="item.id">
                        <!-- 实线 -->
                        <div v-if="item.type == 'text'" @mousedown="startDrag($event, item)"  class="text">Text</div>
                    </template>
                </div>
            </div>
        </div>

        <!-- 拖拽预览元素 -->
        <div v-show="dragPreview.visible" class="drag-preview f fac fpc" :style="{
            left: dragPreview.left + 'px',
            top: dragPreview.top + 'px',
            background: `URL('${dragPreview.imageUrl}') center no-repeat`, 'backgroundSize': 'contain'}"
            >{{ dragPreview.name }}
        </div>

        <!-- 模拟区 -->
        <div class="canvas-conatiner" style="width: 667px;">
            <div style="width: 100%; height: 375px; background-color: #fff;" ref="canvasRef" @mousemove="onMouseMove" @mouseup="stopDrag">
                <template v-for="item in addedDevices" :key="item.instanceId">
                    <!-- 设备 -->
                    <div class="device-item f fac fpc" 
                        v-if="item.type == 'device'"
                        :style="{ left: item.left + 'px', top: item.top + 'px', width: item.width + 'px', height: item.height + 'px', 
                        
                        transform: `translate(-50%, -50%) rotate(${item.rotateDeg || 0}deg) scaleX(${item.reverse == 0 ? 1 : -1})`, transformOrigin: 'center' }"
                        @mousedown="startDrag($event, item)" 
                        @dblclick="removeDevice(item)"
                        >
                        <img :src="item.imageUrl" style="display: block; width: 100%; height: 100%;" alt="">
                    </div>
                    <!-- 实线 -->
                    <div class="line-item f fac fpc" 
                        v-if="item.type == 'line' && item.device == 'line-solid'"
                        :style="{ left: item.left + 'px', top: item.top + 'px', width: item.width + 'px', height: item.height + 'px', background: item.color}"
                        @mousedown="startDrag($event, item)" 
                        @dblclick="removeDevice(item)"
                        >
                    </div>
                    <!-- 虚线 -->
                    <div class="line-item f fac fpc" 
                        v-if="item.type == 'line' && item.device == 'line-dashed'"
                        :style="{ 
                            left: item.left + 'px', top: item.top + 'px', width: item.width + 'px', height: item.height + 'px', 
                            background: item.width > item.height ? 
                            `linear-gradient(90deg, ${item.color} 50%, transparent 0) repeat-x` :
                            `linear-gradient(0deg, ${item.color} 50%, transparent 0) repeat-y`,
                            backgroundSize: item.width > item.height ? 
                            `${item.width / 10}px ${item.height}px` :
                            `${item.width}px ${item.height / 10}px`
                        }"
                        @mousedown="startDrag($event, item)" 
                        @dblclick="removeDevice(item)"
                        >
                    </div>
                    <!-- 箭头 -->
                    <div class="arrowLine-item f fac fpc" 
                        v-if="item.type == 'line' && item.device == 'line-arrow'"
                        :style="{ 
                            left: item.left + 'px', top: item.top + 'px', width: item.width + 'px', height: item.height + 'px', 
                            background: item.color,
                            transform: `translate(-50%, -50%) rotate(${item.rotateDeg || 0}deg) scaleX(${item.reverse == 0 ? 1 : -1})`, transformOrigin: 'center'
                        }"
                        @mousedown="startDrag($event, item)" 
                        @dblclick="removeDevice(item)"
                        >
                        <div :style="{
                            position: 'absolute',
                            width: 0,
                            height: 0,
                            borderStyle: 'solid',
                            ...(item.width > item.height ? {
                                right: '-8px',
                                top: '50%',
                                transform: 'translateY(-50%)',
                                borderWidth: '4px 0 4px 8px',
                                borderColor: `transparent transparent transparent ${item.color}`
                            } : {
                                bottom: '-8px',
                                left: '50%',
                                transform: 'translateX(-50%)',
                                borderWidth: '8px 4px 0 4px',
                                borderColor: `${item.color} transparent transparent transparent`
                            })
                        }"></div>
                    </div>
                    <!-- 圆弧 -->
                    <div class="arrowLine-item f fac fpc" 
                        v-if="item.type == 'line' && item.device == 'line-arc'"
                        :style="{ 
                            left: item.left + 'px', top: item.top + 'px', width: item.width + 'px', height: item.height + 'px', 
                            overflow: 'hidden',
                            transform: `translate(-50%, -50%) rotate(${item.rotateDeg || 0}deg) scaleX(${item.reverse == 0 ? 1 : -1})`, transformOrigin: 'center'
                        }"
                        @mousedown="startDrag($event, item)" 
                        @dblclick="removeDevice(item)"
                        >
                        <div :style="{
                            position: 'absolute',
                            width: item.width > item.height ? item.width + 'px' : item.height + 'px',
                            height: item.width > item.height ? item.width + 'px' : item.height + 'px',
                            borderRadius: '100%',
                            border: `1px solid ${item.color}`,
                            ...(item.width > item.height ? { top: '0%' } : { left: '0%' })
                        }"></div>
                    </div>
                    <!-- 文字 -->
                    <div class="device-item f fac fpc" 
                        v-if="item.type == 'text'"
                        :style="{ left: item.left + 'px', top: item.top + 'px', color: item.color, width: 'fit-content', fontSize: item.width + 'px', whiteSpace: 'nowarp', 
                        transform: `translate(-50%, -50%) rotate(${item.rotateDeg || 0}deg) scaleX(${item.reverse == 0 ? 1 : -1})`, transformOrigin: 'center' }"
                        @mousedown="startDrag($event, item)" 
                        @dblclick="removeDevice(item)"
                        >
                        {{ item.name }}
                    </div>
                </template>
            </div>

            <div class="device-info f fv" v-if="currentDevice">
                <div class="attr">
                    <div class="f fac" v-for="(info, key) in currentDevice">
                        <div>{{ key }}：</div>
                        <div v-if="key == 'name' || key == 'instanceId' || key == 'width' || key == 'height' || key == 'rotateDeg' || key == 'reverse' || key == 'left' || key == 'top'">
                            <el-input size="small" v-model="currentDevice[key]"></el-input>
                        </div>
                        <div v-else>{{ info }}</div>
                        <div v-if="key == 'color'">
                            <el-color-picker v-model="currentDevice[key]"  />
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 代码区 -->
        <div class="code-container f1 f fv" >
            <div class="code-box f1" v-html="markDownText"></div>
            <div class="copy1" @click="copyHTML(markDownText, 'html')">复制</div>
            <div class="copy2" @click="copyHTML(markDownJS, 'js')">复制</div>
            <div class="code-box f1" v-html="markDownJS" style="margin-top: 0.24rem;"></div>
        </div>
    </div>
</template>

<script setup>
import Device from "./Device/Device";
import { Marked } from 'marked';
import { markedHighlight } from "marked-highlight"
import hljs from 'highlight.js'
//引入markdown样式
import 'highlight.js/styles/atom-one-dark.css' 
import { computed } from "vue";

const md = new Marked(
    markedHighlight({
        langPrefix: 'hljs language-',
        highlight(code, lang) {
            const language = hljs.getLanguage(lang) ? lang : 'shell'
            return hljs.highlight(code, { language }).value
        }
  })
)

// 代码结构
const codeHTML = ref('')
const codeJS = ref('')
const markDownText = computed(() => {
    const codeBlock = "```html\n<template>\n    <view class='relative h-full'>" + codeHTML.value + "\n    </view>\n</template>\n<script setup>\n\n</" + "script>"
    return md.parse(codeBlock)
})
const markDownJS = computed(() => {
    const codeBlock = "```javascript\n" + codeJS.value
    return md.parse(codeBlock)
})


// 设备列表
const devices = reactive([
    new Device({ device: 'device-低过省Ⅰ', name: '低过省Ⅰ', type: 'device', imageUrl: '/src/assets/低过省Ⅰ.svg', width: 36, height: 62 }),
    new Device({ device: 'device-调节阀', name: '调节阀', type: 'device', imageUrl: '/src/assets/调节阀.svg', width: 8, height: 8 }),
    new Device({ device: 'device-二吸塔', name: '二吸塔', type: 'device', imageUrl: '/src/assets/二吸塔.svg', width: 28, height: 98 }),
    new Device({ device: 'device-焚硫炉&废热锅炉', name: '焚硫炉&废热锅炉', type: 'device', imageUrl: '/src/assets/焚硫炉&废热锅炉.svg', width: 178, height: 54 }),
    new Device({ device: 'device-风机', name: '风机', type: 'device', imageUrl: '/src/assets/风机.svg', width: 15, height: 14 }),
    new Device({ device: 'device-风机-右', name: '风机-右', type: 'device', imageUrl: '/src/assets/风机-右.svg', width: 13, height: 14 }),
    new Device({ device: 'device-干燥塔', name: '干燥塔', type: 'device', imageUrl: '/src/assets/干燥塔.svg', width: 22, height: 78 }),
    new Device({ device: 'device-高过', name: '高过', type: 'device', imageUrl: '/src/assets/高过.svg', width: 26, height: 36 }),
    new Device({ device: 'device-快速阀', name: '快速阀', type: 'device', imageUrl: '/src/assets/快速阀.svg', width: 8, height: 8 }),
    new Device({ device: 'device-冷换', name: '冷换', type: 'device', imageUrl: '/src/assets/冷换.svg', width: 20, height: 62 }),
    new Device({ device: 'device-盲板', name: '盲板', type: 'device', imageUrl: '/src/assets/盲板.svg', width: 3, height: 6 }),
    new Device({ device: 'device-球阀', name: '球阀', type: 'device', imageUrl: '/src/assets/球阀.svg', width: 8, height: 4 }),
    new Device({ device: 'device-热换', name: '热换', type: 'device', imageUrl: '/src/assets/热换.svg', width: 20, height: 62 }),
    new Device({ device: 'device-省Ⅱ', name: '省Ⅱ', type: 'device', imageUrl: '/src/assets/省Ⅱ.svg', width: 36, height: 36 }),
    new Device({ device: 'device-手阀', name: '手阀', type: 'device', imageUrl: '/src/assets/手阀.svg', width: 8, height: 4 }),
    new Device({ device: 'device-烟囱', name: '烟囱', type: 'device', imageUrl: '/src/assets/烟囱.svg', width: 22, height: 80 }),
    new Device({ device: 'device-预热炉', name: '预热炉', type: 'device', imageUrl: '/src/assets/预热炉.svg', width: 24, height: 12 }),
    new Device({ device: 'device-预热器', name: '预热器', type: 'device', imageUrl: '/src/assets/预热器.svg', width: 16, height: 64 }),
    new Device({ device: 'device-转化器', name: '转化器', type: 'device', imageUrl: '/src/assets/转化器.svg', width: 84, height: 162 }),
    new Device({ device: 'device-HRS塔', name: 'HRS塔', type: 'device', imageUrl: '/src/assets/HRS塔.svg', width: 28, height: 90 }),
    new Device({ device: 'device-精溜槽', name: '精溜槽', type: 'device', imageUrl: '/src/assets/精溜槽.svg', width: 165, height: 29 }),
    new Device({ device: 'device-泵', name: '泵', type: 'device', imageUrl: '/src/assets/泵.svg', width: 12, height: 12 }),
    new Device({ device: 'device-矩形', name: '矩形', type: 'device', imageUrl: '/src/assets/矩形.svg', width: 12, height: 6 }),
    new Device({ device: 'device-圆', name: '圆', type: 'device', imageUrl: '/src/assets/圆.svg', width: 12, height: 12 }),
    new Device({ device: 'device-酸冷却器', name: '酸冷却器', type: 'device', imageUrl: '/src/assets/酸冷却器.svg', width: 52, height: 17 }),
    new Device({ device: 'device-循环槽', name: '循环槽', type: 'device', imageUrl: '/src/assets/循环槽.svg', width: 105, height: 33 }),
    new Device({ device: 'device-地下槽', name: '地下槽', type: 'device', imageUrl: '/src/assets/地下槽.svg', width: 99, height: 29 }),
    new Device({ device: 'device-蝶阀', name: '蝶阀', type: 'device', imageUrl: '/src/assets/蝶阀.svg', width: 4, height: 8 }),
    new Device({ device: 'device-尾吸装置', name: '尾吸装置', type: 'device', imageUrl: '/src/assets/尾吸装置.svg', width: 28, height: 64 }),

    new Device({ device: 'line-solid', name: '实线', type: 'line', color: '#808080',  width: 100, height: 1 }),
    new Device({ device: 'line-dashed', name: '虚线', type: 'line', color: '#000',  width: 100, height: 1 }),
    new Device({ device: 'line-arrow', name: '箭头', type: 'line', color: '#808080',  width: 100, height: 1 }),

    
    new Device({ device: 'line-arc', name: '圆弧', type: 'line', color: '#808080', width: 16, height: 8 }),

    new Device({ device: 'text', name: 'text', type: 'text', color: '#808080', width: 8 })
])

// 已经在渲染的列表
let addedDevices = reactive([])

// 拖拽相关状态
const isDragging = ref(false)
let currentDevice = ref(null)

// 获取模拟区的边界
const canvasRef = ref(null);

// 拖拽时预览对象
const dragPreview = reactive({
    visible: false,
    left: -1000,
    top: -1000,
    name: '',
    imageUrl: ''
})

// 缩放设备
const scaleDevice = (scale, type) => {
    addedDevices.forEach(item => {
        if (item.instanceId == currentDevice.value.instanceId) {
            if (type == 'width') {
                if (scale) {
                    currentDevice.value.width += 1
                } else {
                    if (currentDevice.value.width <= 1) return
                    currentDevice.value.width -= 1
                }
            } else {
                if (scale) {
                    currentDevice.value.height += 1
                } else {
                    if (currentDevice.value.height <= 1) return
                    currentDevice.value.height -= 1
                }
            }
            return
        }
    })
}

// 删除设备
const removeDevice = (device) => {
    const index = addedDevices.findIndex(d => d.instanceId === device.instanceId)
    if (index !== -1) {
        addedDevices.splice(index, 1);
    }
    codeGenerate()
    if (addedDevices.length == 0) {
        currentDevice.value = null
    }
}

// 开始拖拽
const startDrag = (event, device) => {
    isDragging.value = true
    currentDevice.value = device;
    
    console.log('开始拖拽');
    
    // 添加鼠标移动和松开事件
    window.addEventListener('mousemove', onMouseMove)
    window.addEventListener('mouseup', stopDrag)

    // 模拟区设备再次拖拽
    if (device.isAdded) return

    // 初始化预览样式
    dragPreview.visible = true
    dragPreview.name = device.name
    dragPreview.imageUrl = device.imageUrl
}

// 拖拽过程
const onMouseMove = (event) => {
    if (!isDragging.value || !currentDevice.value) return;

    const canvasRect = canvasRef.value.getBoundingClientRect();

    // 左侧设备列表宽度
    const listWidth = canvasRect.x
    // 模拟区宽/高
    const canvasWidth = canvasRect.width
    const canvasHeight = canvasRect.height

    // 拖拽显示虚影的位置与边界限制
    const halfWidth = currentDevice.value.width / 2;
    const halfHeight = currentDevice.value.height / 2;

    // 右侧边界限制
    if (event.clientX + halfWidth >= canvasRect.right) {
        dragPreview.left = canvasRect.right - halfWidth
        currentDevice.value.left = canvasWidth - halfWidth
    } else {
        dragPreview.left = event.clientX
        currentDevice.value.left = event.clientX - listWidth
    }

    // 左侧边界限制（对于已添加设备）
    if (currentDevice.value.isAdded) {
        if (event.clientX - halfWidth <= listWidth) {
            currentDevice.value.left = halfWidth
        }
        // 右侧边界限制（对于已添加设备）
        if (event.clientX + halfWidth >= canvasRect.right) {
            currentDevice.value.left = canvasWidth - halfWidth
        }
    }   

    // 下边界限制
    if (event.clientY + halfHeight >= canvasRect.bottom) {
        dragPreview.top = canvasRect.bottom - halfHeight
        currentDevice.value.top = canvasHeight - halfHeight
        return
    }
    // 上边界限制
    if (event.clientY <= canvasRect.top + halfHeight) {
        dragPreview.top = canvasRect.top + halfHeight
        currentDevice.value.top = halfHeight
        return
    }
    dragPreview.top = event.clientY
    currentDevice.value.top = event.clientY - canvasRect.top
}

// 停止拖拽
const stopDrag = () => {
    if (!isDragging.value || !currentDevice.value) return;

    const canvasRect = canvasRef.value.getBoundingClientRect();

    // canvas区域宽度
    const canvasWidth = canvasRect.width
    const canvasHeight = canvasRect.height

    // 计算设备半宽高
    const halfWidth = currentDevice.value.width / 2;
    const halfHeight = currentDevice.value.height / 2;

    // 隐藏拖拽虚影
    dragPreview.visible = false

    if (currentDevice.value.left > 0) {
        // 边界处理（这块其实可以不要，但是去掉的话在左侧设备区域停止拖拽虚影，虚影会停留在这）
        if (currentDevice.value.left < halfWidth) {
            currentDevice.value.left = halfWidth
        }
        if (currentDevice.value.top < halfHeight) {
            currentDevice.value.top = halfHeight
        }
        if (currentDevice.value.left > canvasWidth - halfWidth) {
            currentDevice.value.left = canvasWidth - halfWidth
        }
        if (currentDevice.value.top > canvasHeight - halfHeight) {
            currentDevice.value.top = canvasHeight - halfHeight
        }

        if(!currentDevice.value.isAdded) {
            addDeviceToArea(currentDevice.value)
        }
    }
   
    isDragging.value = false
    // currentDevice.value = null

    console.log('结束拖拽');

    // 移除事件监听
    window.removeEventListener('mousemove', onMouseMove);
    window.removeEventListener('mouseup', stopDrag);

    codeGenerate()
}

// 复制结构
const copyHTML = async (text, type) => {
    let codeBlock = ''
    if (type == 'html') {
        codeBlock = "<template>\n    <view class='relative h-full'>" + text + "\n    </view>\n</template>\n<script setup>\n\n</" + "script>"
    } else {
        codeBlock = codeJS.value
    }
    try {
        await navigator.clipboard.writeText(codeBlock);
        // 可以添加成功提示
        ElMessage({
            message: '内容已复制到剪贴板',
            type: 'success',
        })
    } catch (err) {
        // 如果 Clipboard API 不可用，使用备用方法
        fallbackCopyTextToClipboard(codeBlock);
    }

    // 备用复制方法
    function fallbackCopyTextToClipboard(text) {
        const textArea = document.createElement('textarea')
        textArea.value = text
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        try {
            const successful = document.execCommand('copy');
            if (successful) {
                 ElMessage({
                    message: '内容已复制到剪贴板',
                    type: 'success',
                })
            }
        } catch (err) {
             ElMessage({
                message: '复制失败，请手动复制',
                type: 'error',
            })
        }
        document.body.removeChild(textArea);
    }
}

// 代码生成
const codeGenerate = () => {
    let codeStr = ''
    let solidLines = []
    let dashedLines = []
    let arrowLines = []
    let arcLines = []
    let texts = []
    addedDevices.forEach(item => {
        let str = ''
        if (item.type == 'device') {
            str = `
                <!-- ${item.name} -->
                <view class='absolute z-10' :style="{ top: ${item.top - item.height / 2} + 'rpx', left: adaptPx(${item.left - item.width / 2}) + 'px', width: adaptPx(${item.width}) + 'px', height: ${item.height}+ 'rpx', background: 'url(${item.imageUrl}) center no-repeat', backgroundSize: 'contain', transform: 'rotate(${item.rotateDeg || 0}deg) scaleX(${item.reverse == 0 ? 1 : -1})', transformOrigin: 'center'}"></view>
            `
        } 
        codeStr += str
        if (item.type == 'line') {
            if (item.device == 'line-solid') {
                solidLines.push({...item})
            } else if (item.device == 'line-dashed') {
                dashedLines.push({...item})
            } else if (item.device == 'line-arrow') {
                arrowLines.push({...item})
            } else if (item.device == 'line-arc') {
                arcLines.push({...item})
            }
        } else if (item.type == 'text') {
            texts.push({...item})
        }
    })
    // 线段添加
    let solidStr = `
        <!-- 实线 -->
        <view class='absolute z-10' v-for='item in solidLines' :id="item.instanceId" :style="{ top: item.top - item.height / 2 + 'rpx', left: adaptPx(item.left - item.width / 2) + 'px', width: adaptPx(item.width) + 'px', height: item.height + 'rpx', background: item.color, transform: \`rotate(\${item.rotateDeg || 0}deg) scaleX(\${item.reverse == 0 ? 1 : -1})\`, transformOrigin: 'center' }"></view>
    `
    let dashedStr = `
        <!-- 虚线 -->
        <view class='absolute z-10' v-for='item in dashedLines' :id="item.instanceId" :style="{ top: item.top - item.height / 2 + 'rpx', left: adaptPx(item.left - item.width / 2) + 'px', width: adaptPx(item.width) + 'px', height: item.height + 'rpx', background: item.color, transform: \`rotate(\${item.rotateDeg || 0}deg) scaleX(\${item.reverse == 0 ? 1 : -1})\`, transformOrigin: 'center', background: item.width > item.height ? \`linear-gradient(90deg, \${item.color} 50%, transparent 0) repeat-x\` : \`linear-gradient(0deg, \${item.color} 50%, transparent 0) repeat-y\`, backgroundSize: item.width > item.height ? \`\${item.width / 10}px \${item.height}px\` : \`\${item.width}px \${item.height / 10}px\`}"></view>
    `
    let arrowStr = `
        <!-- 箭头 -->
        <view class='absolute z-10' v-for='item in arrowLines' :id="item.instanceId" :style="{ top: item.top - item.height / 2 + 'rpx', left: adaptPx(item.left - item.width / 2) + 'px', width: adaptPx(item.width) + 'px', height: item.height + 'rpx', background: item.color, transform: \`rotate(\${item.rotateDeg || 0}deg) scaleX(\${item.reverse == 0 ? 1 : -1})\`, transformOrigin: 'center' }">
            <view v-if='item.device == "line-arrow"' :class="['arrow', item.width > item.height ? 'arrowRight' : 'arrowTop']" :style="{'border-color': item.width > item.height ? \`transparent transparent transparent \${item.color}\` : \`\${item.color} transparent transparent transparent\`}"></view>
        </view>
    `
    let arcStr = `
        <!-- 圆弧 -->
        <view class='absolute z-10' v-for='item in arcLines' :id="item.instanceId" :style="{ top: item.top - item.height / 2 + 'rpx', left: adaptPx(item.left - item.width / 2) + 'px', width: adaptPx(item.width) + 'px', height: item.height + 'rpx', transform: \`rotate(\${item.rotateDeg || 0}deg) scaleX(\${item.reverse == 0 ? 1 : -1})\`, transformOrigin: 'center', 'overflow': 'hidden' }">
            <view v-if='item.device == "line-arc"' class='arc' :style="{'border-color': item.color, 'position': 'absolute', 'width': item.width > item.height ? adaptPx(item.width) + 'px' : item.height + 'rpx', 'height': item.width > item.height ? adaptPx(item.width) + 'px' : item.height + 'rpx', 'borderRadius': '100%', ...(item.width > item.height ? { 'top': '0%' } : { 'left': '0%' })}"></view>
        </view>
    `
    let textStr = `
        <!-- 文字 -->
        <view class='absolute z-10' v-for='item in texts' :id="item.instanceId" :style="{ top: item.top - item.height / 2 + 'rpx', left: adaptPx(item.left - item.width / 2) + 'px', transform: \`rotate(\${item.rotateDeg || 0}deg) scaleX(1)\`, transformOrigin: 'center', 'overflow': 'hidden', 'color': item.color, 'font-size': item.width + 'rpx' }">
            {{ item.name }}
        </view>
    `
    codeStr += solidStr
    codeStr += dashedStr
    codeStr += arrowStr
    codeStr += arcStr
    codeStr += textStr

    codeHTML.value = codeStr

    console.log('实线', JSON.stringify(solidLines));
    console.log('虚线', JSON.stringify(dashedLines));
    console.log('箭头', JSON.stringify(arrowLines));
    console.log('圆弧', JSON.stringify(arcLines));
    console.log('文字', JSON.stringify(texts));

    codeJS.value = `const solidLines = ${JSON.stringify(solidLines)}\n const dashedLines = ${JSON.stringify(dashedLines)}\n const arrowLines = ${JSON.stringify(arrowLines)}\n const arcLines = ${JSON.stringify(arcLines)}\n const texts = ${JSON.stringify(texts)}`
    localStorage.setItem("device", JSON.stringify(addedDevices))
}

// 将设备添加到模拟区域
const addDeviceToArea = (device) => {
    // 确保 device 存在
    if (!device) return; 
    // 复制
    const newDevice = Object.assign(Object.create(Object.getPrototypeOf(device)), device);
    // 更新实例ID，确保唯一
    newDevice.updateInstanceId()
    // 在模拟区再次拖拽标识
    newDevice.isAdded = true

    addedDevices.push(newDevice);
};

onBeforeMount(() => {
    addedDevices = JSON.parse(localStorage.getItem('device')) || []

    codeGenerate()
})

</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 100vh;
    overflow-y: hidden;
    position: relative;
    .device-panel {
        width: 18%;
        height: 100%;
        overflow-y: auto;
        border-right: 0.01rem solid #ccc;
        position: relative;
        .title {
            font-size: 0.2rem;
            font-weight: 700;
            text-align: center;
            height: 0.5rem;
            line-height: 0.5rem;
            border-bottom: 0.01rem solid #eee;
            border-right: 0.01rem solid #ccc;
            background-color: #f3f4f6;
            width: 18%;
            position: fixed;
            top: 0;
            left: 0;
        }
        .list {
            margin-top: 0.24rem;
            padding: 0.5rem 0.1rem 0 0.1rem;
            .name {
                text-align: center;
                color: #ccc;
                margin-bottom: 0.24rem;
                font-size: 0.16rem;
                .n { color: #000;}
            }
            .box {
                width: 100%;
                flex-wrap: wrap;
                .item {
                    width: 1rem;
                    height: 1rem;
                    margin-bottom: 0.12rem;
                    user-select: none;
                    cursor: move;
                    img {
                        width: 100%;
                        height: 100%;
                        display: block;
                    }
                }
                .line {
                    width: 80%;
                    height: 0.2rem;
                    background-color: #000;
                    margin: auto;
                    margin-bottom: 0.12rem;
                    position: relative;
                }
                .dashed {
                    background: linear-gradient(90deg, #000 50%, transparent 0) repeat-x;
                    background-size: 0.1rem 0.2rem; /* 每个虚线段的长度和高度 */
                }
                .arc-line {
                    width: 1rem;
                    height: 0.5rem;
                    overflow: hidden;
                    position: relative;
                    margin: auto;
                    .arc {
                       position: absolute;
                       border-radius: 100%;
                       border: 0.04rem solid #000;
                       width: 1rem;
                       height: 1rem;
                       top: 0%;
                    }
                }
                .arrow {
                    &::after {
                        content: '';
                        position: absolute;
                        right: -0.2rem;
                        top: 50%;
                        transform: translateY(-50%);
                        width: 0;
                        height: 0;
                        border-left: 0.2rem solid #000;
                        border-top: 0.2rem solid transparent;
                        border-bottom: 0.2rem solid transparent;
                    }
                }
                .text {
                    user-select: none;
                }
            }
        }
    }
    .drag-preview {
        position: absolute;
        width: 1rem;
        height: 1rem;
        user-select: none;
        cursor: move;
        transform: translate(-50%, -50%); 
        will-change: transform; // 优化动画性能
        opacity: 0.7;
        pointer-events: none; 
        z-index: 9999; 
    }
    .canvas-conatiner {
        height: 100%;
        position: relative;
        background-color: pink;
        .device-item {
            position: absolute;
            user-select: none;
            // cursor: move;
            transform: translate(-50%, -50%); // 中心点对齐
            will-change: transform; // 优化动画性能
        }
        .line-item {
            position: absolute;
            user-select: none;
            transform: translate(-50%, -50%); // 中心点对齐
            will-change: transform; // 优化动画性能
        }
        .arrowLine-item {
            position: absolute;
            user-select: none;
            transform: translate(-50%, -50%); // 中心点对齐
            will-change: transform; // 优化动画性能
        }
        .device-info {
            margin-top: 0.24rem;
            .attr {
                padding-left: 0.24rem;
            }
        }
    }
    .code-container {
        padding: 0.24rem;
        height: 100%;
        overflow-y: hidden;
        position: relative;
        .code-box {
            width: 100%;
            height: 100%;
            overflow-y: auto;
        }
        .copy1,
        .copy2 {
            position: absolute;
            top: 0.24rem;
            right: 0.24rem;
            background-color: #fff;
            padding: 0.04rem 0.12rem;
            cursor: pointer;
        }
        .copy2 {
            top: calc(50% + 0.12rem);
        }
    }
}
</style>